package sk.stuba.fiit.clientApp.gui.handler;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JTable;
import sk.stuba.fiit.clientApp.cvo.FileDetailCVO;
import sk.stuba.fiit.clientApp.gui.model.FileTableModel;

/**
 * Trieda zodpovedná za pridanie vybraného súboru do modelu tabuľky
 * @author Marek Hruška
 *
 */
public class AddButtonFileActionListener implements ActionListener{

	JTable table;
	
	public AddButtonFileActionListener(JTable table) {
		this.table = table;
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		  JFileChooser chooser = new JFileChooser();
		     chooser.setMultiSelectionEnabled(false);
		     int option = chooser.showOpenDialog(null);
		     if (option == JFileChooser.APPROVE_OPTION) {
		       File selectedFile = chooser.getSelectedFile();
		       ((FileTableModel)table.getModel()).addFiles(copyFromFileToFileDetailCVO(selectedFile));
		     }		     
	}
	
	 private FileDetailCVO copyFromFileToFileDetailCVO(File file){
		 FileDetailCVO result = new FileDetailCVO();
		   String[] name = file.getName().split("\\.");
	       if(name.length>1){
	    	   result.setName(name[0]);
	    	   result.setExtension(name[name.length-1]);
	       }else{
		       result.setName(name[name.length-1]);
		       result.setExtension("");

	       }
			result.setPath(file.getAbsolutePath());
			result.setSize(file.length());
		 return result;
     }

}
